package com.canal.admin.handler;

import com.canal.admin.response.ResultUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.canal.admin.response.Result;
import org.springframework.security.authentication.*;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @author Administrator
 * @description
 * @date 2019年03月16 12:41
 */
public class LoginFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException e)
            throws IOException, ServletException {
        ObjectMapper mapper = new ObjectMapper();
        Result result = new Result();
        if (e instanceof BadCredentialsException ||
                e instanceof UsernameNotFoundException) {
            result = ResultUtil.makeFailure("账户名或者密码输入错误!");
        } else if (e instanceof LockedException) {
            result = ResultUtil.makeFailure("账户被锁定，请联系管理员!");
        } else if (e instanceof CredentialsExpiredException) {
            result = ResultUtil.makeFailure("密码过期，请联系管理员!");
        } else if (e instanceof AccountExpiredException) {
            result = ResultUtil.makeFailure("账户过期，请联系管理员!");
        } else if (e instanceof DisabledException) {
            result = ResultUtil.makeFailure("账户被禁用，请联系管理员!");
        } else {
            result = ResultUtil.makeFailure("登录失败!");
        }
        String jsonResult = mapper.writeValueAsString(result);
        response.setContentType("application/json;charset=utf8");
        PrintWriter writer = response.getWriter();
        writer.write(jsonResult);
        writer.flush();
        writer.close();
    }
}
